//
//  GridConnectedView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/4.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxGesture
import Rswift
class GridConnectedViewModel: NSObject {
    var pvd_id: String = ""
    var connected_type: GridConnectedValue = .offGrid {
        didSet{
            self.connected_type_value = self.connected_type.rawValue
        }
    }
    @objc dynamic var isNMIRequired: Bool = false
    @objc dynamic var connected_type_value: String = GridConnectedValue.offGrid.rawValue
    @objc dynamic var nmi: String = ""
    @objc dynamic var gridConnectionApplicationRefNo: String = ""
}
class GridConnectedView: View {
    fileprivate lazy var disposeBag = DisposeBag()
    @objc dynamic var viewModel = GridConnectedViewModel()
    let onGridLabel = OptionTypeLabel(GridConnectedName.onGrid.rawValue)
    let offGridLabel = OptionTypeLabel(GridConnectedName.offGrid.rawValue)
    let contentView = View()
    let NMITextfield = TextFieldWithRequiredView(.nmi)
    let gridConnectionApplicationRefNoTextfield = DIYTextField()
    override func setUpView() {
        //grid connected title
        let gridConnectedTitle = ContentLabel()
        gridConnectedTitle.text = R.string.localizable.connectType()
        self.addSubview(gridConnectedTitle)
        gridConnectedTitle.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.size.greaterThanOrEqualTo(0)
        }
        //
        //backView
        self.addSubview(onGridLabel)
        onGridLabel.snp.makeConstraints { make in
            make.top.equalTo(gridConnectedTitle.snp.bottom).offset(12)
            make.left.equalTo(gridConnectedTitle)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(0)
        }
        //backView
        self.addSubview(offGridLabel)
        offGridLabel.snp.makeConstraints { make in
            make.centerY.equalTo(onGridLabel)
            make.left.equalTo(onGridLabel.snp.right).offset(8)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.width.equalTo(onGridLabel)
        }
        //
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.equalTo(onGridLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(onGridLabel)
            make.right.equalTo(offGridLabel)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //监听on grid的监听事件
        onGridLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectConnectType(.onGrid)
        }).disposed(by: self.disposeBag)
        //监听on grid的监听事件
        offGridLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectConnectType(.offGrid)
        }).disposed(by: self.disposeBag)
        
        //监听nmi的监听事件
        self.NMITextfield.editingDidEndClosure =  { [weak self] (data) in
            guard let strongSelf = self else {return}
            strongSelf.viewModel.nmi = data
        }
        //监听文本编辑gridConnectionApplicationRefNoTextfield
        self.gridConnectionApplicationRefNoTextfield.rx.controlEvent([.editingDidEnd]).asObservable().subscribe(onNext: {[weak self]  in
            guard let strongSelf = self else {return}
            strongSelf.viewModel.gridConnectionApplicationRefNo = (strongSelf.gridConnectionApplicationRefNoTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
        }).disposed(by: self.disposeBag)
    }
    private func selectConnectType(_ type: GridConnectedValue){
        self.viewModel.connected_type = type
        self.onGridLabel.setUnSelect()
        self.offGridLabel.setUnSelect()
        self.setContentView(self.viewModel.connected_type)
        //on grid开关，自动获取焦点
        if self.viewModel.connected_type == GridConnectedValue.onGrid{
            self.NMITextfield.textField.becomeFirstResponder()
            self.onGridLabel.setSelect()
        }else{
            self.offGridLabel.setSelect()
            self.endEditing(true)
        }
    }
    func setData(_ model: GridConnectedViewModel,editFlag: Bool = false){
        self.viewModel = model
        self.NMITextfield.textField.text = self.viewModel.nmi
        self.gridConnectionApplicationRefNoTextfield.text = self.viewModel.gridConnectionApplicationRefNo
        switch self.viewModel.connected_type {
        case GridConnectedValue.onGrid:
            self.onGridLabel.setSelect()
            self.offGridLabel.setUnSelect()
        case GridConnectedValue.offGrid:
            self.offGridLabel.setSelect()
            self.onGridLabel.setUnSelect()
        }
        self.setContentView(self.viewModel.connected_type)
        if editFlag {
            self.validateAllRequiredFieldWhenEdit()
        }
    }
    //MARK: - 根据是否开启了on grid，显示内容
    private func setContentView(_ connectType: GridConnectedValue){
        if connectType == .onGrid {//on grid
            //nmi title
            let NMITitle = self.viewModel.isNMIRequired ? LabelWithRedStarView(R.string.localizable.nationalMeterIdentifier()) : ContentLabel(text: R.string.localizable.nationalMeterIdentifier())
            contentView.addSubview(NMITitle)
            NMITitle.snp.makeConstraints { make in
                make.top.left.equalToSuperview()
                make.size.greaterThanOrEqualTo(0)
            }
            //
            NMITextfield.needCheckFlag = self.viewModel.isNMIRequired
            contentView.addSubview(NMITextfield)
            NMITextfield.snp.makeConstraints { make in
                make.top.equalTo(NMITitle.snp.bottom).offset(Constant.TitleTextMargin)
                make.left.right.equalToSuperview()
                make.height.greaterThanOrEqualTo(0)
            }
            //nmi title
            let gridConnectionApplicationRefNoTitle = ContentLabel()
            gridConnectionApplicationRefNoTitle.text = R.string.localizable.gridConnectionApplicationRefNo()
            contentView.addSubview(gridConnectionApplicationRefNoTitle)
            gridConnectionApplicationRefNoTitle.snp.makeConstraints { make in
                make.top.equalTo(NMITextfield.snp.bottom).offset(Constant.TopBottomMargin)
                make.left.equalToSuperview()
                make.size.greaterThanOrEqualTo(0)
            }
            //tip btn
            let gridConnectionApplicationRefNoTipBtn = UIButton()
            gridConnectionApplicationRefNoTipBtn.setImage(R.image.installation_detail_spv_tip_icon(), for: UIControl.State.normal)
            contentView.addSubview(gridConnectionApplicationRefNoTipBtn)
            gridConnectionApplicationRefNoTipBtn.snp.makeConstraints { (make) in
                make.centerY.equalTo(gridConnectionApplicationRefNoTitle)
                make.left.equalTo(gridConnectionApplicationRefNoTitle.snp.right)
                make.height.width.equalTo(40)
            }
            //
            contentView.addSubview(gridConnectionApplicationRefNoTextfield)
            gridConnectionApplicationRefNoTextfield.snp.makeConstraints { make in
                make.top.equalTo(gridConnectionApplicationRefNoTitle.snp.bottom).offset(Constant.TitleTextMargin)
                make.left.right.equalToSuperview()
                make.height.equalTo(DIYTextField.height)
                make.bottom.equalToSuperview()
            }
            //gridConnectionApplicationRefNo tip btn
            gridConnectionApplicationRefNoTipBtn.rx.tap.subscribe { [weak self] (data)in
                guard let strongSelf = self else {return }
                PopViewUtil.shared.showPopView(R.string.localizable.whenYouApplyForAGridConnectionTheNetworkServiceProviderNSPWillProvideYouWithAnApplicationReferenceNumber(),tipBtn: gridConnectionApplicationRefNoTipBtn, position: .up, contentView: strongSelf)
            }.disposed(by: self.disposeBag)
            
        }else{//off grid
            for subview in self.contentView.subviews{
                subview.removeFromSuperview()
            }
        }
        
    }
    //MARK: - 只用于已创建Job的信息编辑， 进入编辑界面如果save 按钮不可用，要给与相应提示
    private func validateAllRequiredFieldWhenEdit(){
        if self.viewModel.connected_type == .onGrid {
            self.NMITextfield.checkTextIfValid()
        }
    }
}
